package com.itheima.app.manager;

import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.*;
import com.itheima.service.db.TestSoulService;
import com.itheima.util.TestSoulUtil;
import com.itheima.vo.OptionsVo;
import com.itheima.vo.QuestionsVo;
import com.itheima.vo.ReportVo;
import com.itheima.vo.SurveyVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Autor JiangYunTian
 * @Date 2022/11/10
 * @Function 测灵魂Manager
 */
@Component
public class TestSoulManager {

    @DubboReference
    private TestSoulService testSoulService;

    //测灵魂查询问卷
    public ResponseEntity findQuestionnaire() {

        //获取用户id
        Long userId = UserHolder.get().getId();

        //判断用户是否有问卷锁状态记录
        List<QuestionUserLock> questionUserLockList = testSoulService.findQuestionUserLockByUserId(userId);

        //若无,则为用户添加初始的问卷锁状态
        if (questionUserLockList.size() == 0) {
            QuestionUserLock questionUserLock1 = new QuestionUserLock();
            QuestionUserLock questionUserLock2 = new QuestionUserLock();
            QuestionUserLock questionUserLock3 = new QuestionUserLock();
            questionUserLock1.setUserId(userId);
            questionUserLock2.setUserId(userId);
            questionUserLock3.setUserId(userId);
            questionUserLock1.setSurveyId(1L);
            questionUserLock2.setSurveyId(2L);
            questionUserLock3.setSurveyId(3L);
            questionUserLock1.setIsLock(0);
            questionUserLock2.setIsLock(1);
            questionUserLock3.setIsLock(1);
            testSoulService.saveQuestionUserLock(questionUserLock1);
            testSoulService.saveQuestionUserLock(questionUserLock2);
            testSoulService.saveQuestionUserLock(questionUserLock3);
        }

        //更新一下锁状态记录
        List<QuestionUserLock> lockList = testSoulService.findQuestionUserLockByUserId(userId);

        //初始化SurveyVoList用于返回数据
        //{数据结构:SurveyVoList<-SurveyVo<-QuesiontsVoList<-QuesiontsVo<-OptionsVoList<-OptionsVo}
        List<SurveyVo> surveyVoList = new ArrayList<>();

        //初始化surveyIdList用于存储问卷id
        List<Long> surveyIdList = new ArrayList<>();

        //将锁状态的数据遍历封装进surveyVo
        for (QuestionUserLock questionUserLock : lockList) {
            SurveyVo surveyVo = new SurveyVo();
            surveyVo.setId(questionUserLock.getSurveyId().toString());
            surveyVo.setIsLock(questionUserLock.getIsLock());
            surveyVoList.add(surveyVo);

            //将问卷id封装进id集合
            surveyIdList.add(questionUserLock.getSurveyId());
        }

        //通过问卷id查询问卷属性
        List<Survey> surveyList = testSoulService.findSurveyBySurveyIdList(surveyIdList);

        //将问卷属性封装进Vo
        for (Survey survey : surveyList) {
            for (SurveyVo surveyVo : surveyVoList) {
                //通过问卷id的比对来封装对象
                if (survey.getId().toString().equals(surveyVo.getId())) {

                    surveyVo.setName(survey.getName());
                    surveyVo.setLevel(survey.getLevel());
                    surveyVo.setCover(survey.getCover());
                    surveyVo.setStar(survey.getStar());

                    //后面改,暂时无
                    Report report = testSoulService.findReportByUserIdAndSurveyId(userId, survey.getId());

                    if (report != null) {
                        surveyVo.setReportId(report.getId().toString());
                    } else {
                        surveyVo.setReportId(null);
                    }
                }
            }
        }

        //开始封装SurveyVo<-QuesiontsVoList
        for (SurveyVo surveyVo : surveyVoList) {
            //通过surveyId查询问题
            List<Questions> questionsList = testSoulService.findQuestionsBySurveyId(Long.parseLong(surveyVo.getId()));

            //初始化questionsVoList,存放问题
            List<QuestionsVo> questionsVoList = new ArrayList<>();

            //遍历
            //开始封装QuesiontsVo<-OptionsVoList
            for (Questions questions : questionsList) {

                //封装questionsVo
                QuestionsVo questionsVo = new QuestionsVo();
                questionsVo.setId(questions.getId().toString());
                questionsVo.setQuestion(questions.getQuestion());

                //添加到VoList
                questionsVoList.add(questionsVo);

                //封装optionsVo
                List<Options> optionsList = testSoulService.findOptionsByQuestionsId(questions.getId());

                List<OptionsVo> optionsVoList = new ArrayList<>();
                for (Options options : optionsList) {
                    OptionsVo optionsVo = new OptionsVo();

                    //封装optionsVo
                    optionsVo.setOption(options.getOption());
                    optionsVo.setId(options.getId().toString());

                    //添加到VoList
                    optionsVoList.add(optionsVo);
                }
                questionsVo.setOptions(optionsVoList);
            }
            surveyVo.setQuestions(questionsVoList);
        }
        System.out.println(surveyVoList);
        //返回结果
        return ResponseEntity.ok(surveyVoList);
    }

    //提交问卷
    public ResponseEntity submitQuestionnaire(List<Answers> answers) {

        Long userId = UserHolder.get().getId();

        //初始化Report
        Report report = new Report();
        report.setUserId(userId);

        //计算得分
        Integer sum = testSoulService.calculateScore(answers);

        //得到该问卷的id(根据id也可判断等级,1=初级,2=中级,3=高级)
        Long surveyId = testSoulService.findSurveyIdByAnswers(answers);

        //如果问卷为初级,直接解锁中级问卷
        if (surveyId == 1L) {
            //得到(下一级)锁对象
            QuestionUserLock questionUserLock = testSoulService.findQuestionUserLockById(userId, surveyId + 1);
            //如果未解锁
            if (questionUserLock.getIsLock() == 1) {
                //解锁
                questionUserLock.setIsLock(0);
                //保存锁对象
                testSoulService.updateQuestionUserLock(questionUserLock);
            }
        }

        //如果问卷为中级,需要满足得分需求解锁高级问卷
        if (surveyId == 2L) {
            if (sum >= 40) {
                //得到(下一级)锁对象
                QuestionUserLock questionUserLock = testSoulService.findQuestionUserLockById(userId, surveyId + 1);
                //如果未解锁
                if (questionUserLock.getIsLock() == 1) {
                    //解锁
                    questionUserLock.setIsLock(0);
                    //保存锁对象
                    testSoulService.updateQuestionUserLock(questionUserLock);
                }
            }
        }

        //封装report
        report.setScore(sum);
        report.setSurveyId(surveyId);

        //根据得分进行分类
        if (sum < 21) {
            //猫头鹰
            report.setConclusion(TestSoulUtil.maoTouYing);
            report.setCover(TestSoulUtil.maoTouYingPic);
        } else if (sum <= 40 && sum >= 21) {
            //白兔型
            report.setConclusion(TestSoulUtil.baiTu);
            report.setCover(TestSoulUtil.baiTuPic);
        } else if (sum <= 55 && sum >= 41) {
            //狐狸型
            report.setConclusion(TestSoulUtil.huLi);
            report.setCover(TestSoulUtil.huLiPic);
        } else {
            //狮子型
            report.setConclusion(TestSoulUtil.shiZi);
            report.setCover(TestSoulUtil.shiZiPic);
        }

        //保存report
        Long reportId = testSoulService.saveOrUpdateReport(report);

        System.out.println(reportId);

        return ResponseEntity.ok(reportId.toString());

    }

    //查看结果
    public ResponseEntity findReportById(String reportId) {
        //通过id获得report对象
        Report report = testSoulService.findReportById(Long.parseLong(reportId));

        //初始化reportVo
        ReportVo reportVo = new ReportVo();

        //初始化容器
        //维度
        List<Dimensions> dimensionsList = new ArrayList<>();

        //初始化四个维度
        Dimensions dimensions1 = new Dimensions();
        Dimensions dimensions2 = new Dimensions();
        Dimensions dimensions3 = new Dimensions();
        Dimensions dimensions4 = new Dimensions();

        //与你相似
        List<SimilarYou> similarYouList = new ArrayList<>();

        //获得问卷的分数
        Integer score = report.getScore();

        //公共属性的封装
        reportVo.setConclusion(report.getConclusion());
        reportVo.setCover(report.getCover());

        dimensions1.setKey(TestSoulUtil.WAI_XIANG);//外向
        dimensions2.setKey(TestSoulUtil.PAN_DUAN);//判断
        dimensions3.setKey(TestSoulUtil.CHOU_XIANG);//抽象
        dimensions4.setKey(TestSoulUtil.LI_XING);//理性

        //为每个维度根据所属类型不同赋值
        if (score < 21) {
            //猫头鹰
            dimensions1.setValue(TestSoulUtil.SEVENTY);
            dimensions2.setValue(TestSoulUtil.EIGHTY);
            dimensions3.setValue(TestSoulUtil.SEVENTY);
            dimensions4.setValue(TestSoulUtil.NINETY);

        } else if (score <= 40 && score >= 21) {
            //白兔型
            dimensions1.setValue(TestSoulUtil.SEVENTY);
            dimensions2.setValue(TestSoulUtil.NINETY);
            dimensions3.setValue(TestSoulUtil.EIGHTY);
            dimensions4.setValue(TestSoulUtil.NINETY);

        } else if (score <= 55 && score >= 41) {
            //狐狸型
            dimensions1.setValue(TestSoulUtil.SEVENTY);
            dimensions2.setValue(TestSoulUtil.SIXTY);
            dimensions3.setValue(TestSoulUtil.SIXTY);
            dimensions4.setValue(TestSoulUtil.SEVENTY);

        } else {
            //狮子型
            dimensions1.setValue(TestSoulUtil.NINETY);
            dimensions2.setValue(TestSoulUtil.NINETY);
            dimensions3.setValue(TestSoulUtil.EIGHTY);
            dimensions4.setValue(TestSoulUtil.SIXTY);
        }

        //将维度放入集合
        dimensionsList.add(dimensions1);
        dimensionsList.add(dimensions2);
        dimensionsList.add(dimensions3);
        dimensionsList.add(dimensions4);

        //封装进reportVo
        reportVo.setDimensions(dimensionsList);

        //查找分数与用户相似的用户
        List<UserInfo> userInfoList = testSoulService.findSimilarYou(report.getSurveyId(), score);

        //遍历封装与你相似对象
        for (UserInfo userInfo : userInfoList) {
            //排除自己
            if (userInfo != null && userInfo.getId() != UserHolder.get().getId()) {
                SimilarYou similarYou = new SimilarYou();
                similarYou.setId(userInfo.getId().intValue());
                similarYou.setAvatar(userInfo.getAvatar());
                similarYouList.add(similarYou);
            }
        }

        //封装similarYou到Vo
        reportVo.setSimilarYou(similarYouList);

        return ResponseEntity.ok(reportVo);
    }
}
